// pages/smartlife/bike/bike.js
var common = require('../../../utils/common.js');
var width = 320
var height = 480
Page({
  data: {
    height:0,
    showLocation:true,
    latitude:0,
    longitude:0,
    nearStationList:[],
    markers: [],
    controls: []
  },
  regionchange(e) {
	var that = this
    console.log(e.type)
	that.setData({
		controls:[{
		id: 1,
		iconPath: '/image/location_notcenter.png',
		position: {
			left: width - 40,
			top: height - 50,
			width: 30,
			height: 30
		},
		clickable: true
		}]
	})
  },
  markertap(e) {
    console.log(e.markerId)
  },
  controltap(e) {
	var that = this
    console.log(e.controlId)
	this.mapCtx.moveToLocation()
	that.setData({
		controls:[{
		id: 1,
		iconPath: '/image/location_center.png',
		position: {
			left: width - 40,
			top: height - 50,
			width: 30,
			height: 30
		},
		clickable: true
		}]
	})
  },
	onShareAppMessage: function () {
    var that = this
    return {
      title: '昆山公共自行车',
      path: '/pages/smartlife/bike/bike'
    }
  },
  onLoad:function(options){
    var that=this
		var appUsed = wx.getStorageSync('appused')
		if (!appUsed) {
				// 跳转到app使用引导页面
				wx.navigateTo({
					url: '/pages/smartlife/guide/guide'
				})
				wx.setStorageSync('appused', true)
		}
    var sys = wx.getSystemInfoSync()
    width = sys.windowWidth
    height = sys.windowHeight
	that.setData({
		controls:[{
		id: 1,
		iconPath: '/image/location_center.png',
		position: {
			left: width - 40,
			top: height - 50,
			width: 30,
			height: 30
		},
		clickable: true
		}]
	})
	wx.showToast({
      title: '加载中',
      icon: 'loading',
      duration:10000
    })
    wx.getLocation({
      type: 'gcj02', // 默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
      success: function(res){
		  that.setData({
			latitude:res.latitude,
			longitude:res.longitude,
		  })
		//   发起请求，获得附近的公交站点
		var lgtlat = common.gcj02tobd09(res.longitude,res.latitude)
		wx.request({
			url: common.trafficUrl()+'bikeStationNearby',
			data: {
				rang:'50000',
				lat:lgtlat[1]+"",
				lgt:lgtlat[0]+""
			},
			success: function(res){
			if(res.data.errcode=="0"){
				// 根据站点信息，编辑markers信息
				var nearStationList = res.data.data
				var markers = that.data.markers
				for(var i=0;i<nearStationList.length;i++){
					var lat = nearStationList[i].at
					var lgt = nearStationList[i].ot
					var lgtlat = common.bd09togcj02(lgt,lat)
					var marker = {
						iconPath: "/image/bike_station.png",
						id: nearStationList[i].id,
						longitude: lgtlat[0],
						latitude: lgtlat[1],
						title:nearStationList[i].nm+'  可借:'+nearStationList[i].lc+' 可停:'+nearStationList[i].rc,
						width: 30,
						height: 30
					}
					markers.push(marker)
				}
				that.setData({
					height:height,
					markers: markers
					})
				}else{
					
				}
				wx.hideToast()
			}
		})
      }
    })
  },
  onReady: function (e) {
    // 使用 wx.createMapContext 获取 map 上下文 
    this.mapCtx = wx.createMapContext('map')
  }
})